package com.example.appstudy2405;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class GuessNumber extends AppCompatActivity implements View.OnClickListener {
    private EditText etGuessNum;
    private String guessRecords;
    private String correctNumber = "";
    private TextView tvGuessRecords;
    // 猜的次数
    private int guessCount;
    // 连续点击3次说明会显示要猜的数字
    private int cheater = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guess_number);
        // 初始化 EditText
        etGuessNum = findViewById(R.id.et_guess_num);
        tvGuessRecords = findViewById(R.id.tv_num_history);

        guessRecords = tvGuessRecords.getText().toString().trim();

        findViewById(R.id.bt_send_num).setOnClickListener(this);
        findViewById(R.id.bt_game_readme).setOnClickListener(this);
        findViewById(R.id.bt_regame).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (R.id.bt_send_num == view.getId()) {
            if (correctNumber.isEmpty()) {
                Toast.makeText(this, "请先点击 新开一局 按钮", Toast.LENGTH_SHORT).show();
            } else {
                String guess_num = etGuessNum.getText().toString().trim();
                guessCount += 1;
                String result = checkGuessNum(guess_num, correctNumber);
                Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
                StringBuilder curRecord = new StringBuilder();
                guessRecords += curRecord.append(guess_num).append(" ").append(result).append("\n").toString();
                tvGuessRecords.setText(guessRecords);
                etGuessNum.setText("");
                if (guess_num.equals(correctNumber)) {
                    showWinDialog();
                }
            }
            cheater = 0;
        } else if (R.id.bt_regame == view.getId()) {
            newGame();
        } else if (R.id.bt_game_readme == view.getId()) {
            cheater += 1;
            showGameReadmeDialog();
            if (cheater >= 3) {
                Toast.makeText(this, correctNumber, Toast.LENGTH_SHORT).show();
                cheater = 0;
            }
//            Toast.makeText(this, "未开发2", Toast.LENGTH_SHORT).show();
        }
    }

    private void newGame() {
        correctNumber = generateRandomFourDigitString();
        Toast.makeText(this, "新的四位数字已生成", Toast.LENGTH_SHORT).show();
        Log.i("bt_regame", correctNumber);
        guessRecords = "";
        tvGuessRecords.setText("");
        guessCount = 0;
    }

    // 传统方式
    private void showWinDialog2() {
        final Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.guess_number_win);
        String message = String.format("恭喜你，答对了！\n您一共猜了 %d 次", guessCount);
        TextView tvWinMessage = dialog.findViewById(R.id.tv_guess_number_win);
        tvWinMessage.setText(message);
        guessCount = 0;
        etGuessNum.setText("");
        correctNumber = "";

        dialog.findViewById(R.id.bt_dialog_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        dialog.findViewById(R.id.bt_dialog_redo).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                newGame();
                dialog.dismiss();
            }
        });

        dialog.show();
    }

    private void showWinDialog() {
        String message = String.format("恭喜你，答对了！\n您一共猜了 %d 次", guessCount);
        guessCount = 0;
        etGuessNum.setText("");
        correctNumber = "";

        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setTitle("游戏结束")
                .setMessage(message)
                .setNegativeButton("好的", null)
                .setPositiveButton("再玩一局", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        newGame();
                    }
                }).create();
        alertDialog.show();
    }

    // 以下为业务逻辑方法
    private String checkGuessNum(String guessNum, String correctNum) {
        // 验证输入是否满足条件
        if (guessNum == null || correctNum == null || guessNum.length() != 4 || correctNum.length() != 4 ||
                !guessNum.matches("\\d{4}") || !correctNum.matches("\\d{4}") ||
                hasUniqueDigits(guessNum) || hasUniqueDigits(correctNum)) {
            return "请输入4位不同的数字";
        }

        // 初始化A和B的计数
        int aCount = 0; // 位置正确的数的个数
        int bCount = 0; // 数字正确而位置不对的数的个数

        // 使用HashMap来存储correctNum中每个数字出现的索引
        Map<Character, Integer> correctNumMap = new HashMap<>();
        for (int i = 0; i < correctNum.length(); i++) {
            char digit = correctNum.charAt(i);
            if (!correctNumMap.containsKey(digit)) {
                correctNumMap.put(digit, i);
            }
        }

        // 遍历guessNum
        for (int i = 0; i < guessNum.length(); i++) {
            char guessDigit = guessNum.charAt(i);
            if (correctNumMap.containsKey(guessDigit)) {
                int correctIndex = correctNumMap.get(guessDigit);
                if (correctIndex == i) {
                    // 位置和数字都正确，A增加
                    aCount++;
                } else {
                    // 数字正确但位置不对，B增加
                    bCount++;
                }
                // 无论哪种情况，都从map中移除该数字，因为不能重复计算
                correctNumMap.remove(guessDigit);
            }
        }

        // 构建并返回结果字符串
        StringBuilder result = new StringBuilder();
        result.append(aCount).append("A");
        result.append(bCount).append("B");
        return result.toString();
    }

    // 辅助方法：检查字符串是否包含唯一的数字
    private boolean hasUniqueDigits(String num) {
        boolean[] digits = new boolean[10]; // 假设只包含0-9的数字
        for (char c : num.toCharArray()) {
            int digit = c - '0';
            if (digits[digit]) {
                return true; // 如果数字已经出现过，则不是唯一的
            }
            digits[digit] = true;
        }
        return false; // 所有数字都是唯一的
    }

    private void showGameReadmeDialog() {
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setTitle("游戏说明")
                .setMessage(R.string.game_readme_text)
                .setNegativeButton("好的", null).create();
        alertDialog.show();
    }

    // 新建 layout 方式
    private void showGameReadmeDialog2() {
        // 使用自定义布局创建Dialog
        final Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.guess_number_readme);

        // 设置确认按钮的点击事件
        dialog.findViewById(R.id.bt_dialog_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss(); // 关闭对话框
            }
        });

        // 如果需要，可以从资源或代码中动态设置文本内容
        TextView tvContent = dialog.findViewById(R.id.tv_game_readme_content);
        tvContent.setText(getResources().getString(R.string.game_readme_text)); // 假设你在strings.xml中定义了游戏说明文本

        dialog.show();
    }

    /**
     * 生成一个包含0-9之间不同数字的4位随机字符串。
     *
     * @return 一个随机的4位数字字符串。
     */
    public static String generateRandomFourDigitString() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();

        while(sb.length() < 4) {
            int digit = random.nextInt(10); // 生成0-9的随机数
            if(!sb.toString().contains(Integer.toString(digit))) {
                sb.append(digit);
            }
        }

        return sb.toString();
    }
}